# Copyright (C) 2007 Laszlo Pandy <laszlok2@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import gtk
import decimal
Dec = decimal.Decimal

from AdventureMoney.core import Utils
from AdventureMoney.core import ShareProfile

import InterfaceUtils
import CalendarEntry as Cal
import AdvancedShareWidget

class NewPaymentDialog:
	
	MAX_DESCRIPTIONS = 17
	
	def __init__(self, parentWindow, account, addPaymentCb):
		self.wTree = InterfaceUtils.GetGladeTree("NewPaymentDialog")
		
		signals = {
			"OnOk"			: self.OnOk,
			"OnCancel"		: self.OnCancel,
			"OnClose"		: self.OnCancel,
			"OnValueChanged"	: self.OnValueChanged,
			"OnCategoryChanged"	: self.OnCategoryChanged,
		}
		
		self.wTree.signal_autoconnect(signals)
		
		self.account = account
		self.parentWindow = parentWindow
		self.addPaymentCb = addPaymentCb
		self.ID = -1
		
		self.window = self.wTree.get_widget("NewPaymentDialog")
		self.window.set_transient_for(parentWindow)
		self.window.set_modal(True)
		
		self.invertButton = self.wTree.get_widget("PaymentInvertSharedButton")
		self.paidByCombo = self.wTree.get_widget("PaymentPaidByCombo")
		self.categoryCombo = self.wTree.get_widget("PaymentCategoryCombo")
		self.valueSpinButton = self.wTree.get_widget("PaymentValueSpin")
		
		self.dateEntry = Cal.CalendarEntry()
		self.topTable = self.wTree.get_widget("table3")
		self.topTable.attach(self.dateEntry, 1, 2, 1, 2)
		
		self.calendarButton = self.wTree.get_widget("CalendarDropDownButton")
		self.descriptionEntry = self.wTree.get_widget("PaymentDescriptionEntry")
		self.commentsTextView = self.wTree.get_widget("PaymentCommentsTextView")
		self.involvedTable = self.wTree.get_widget("PeopleInvolvedTable")
		
		total = self.valueSpinButton.get_text()
		self.shareWidget = AdvancedShareWidget.AdvancedShareWidget(self.account, self.window, total)
		self.involvedTable.attach(self.shareWidget, 1, 2, 2, 3)
		
		# find the 17 most recent descriptions to put in the combo menu
		self.paymentDescs = set()
		for bill in reversed(self.account.getBills()):
			if bill.getDetails():
				self.paymentDescs.add(bill.getDetails())
				if len(self.paymentDescs) >= self.MAX_DESCRIPTIONS:
					break
		
		self.paymentDescs = sorted(self.paymentDescs)
		descModel = gtk.ListStore(str)
		self.descriptionEntry.set_model(descModel)
		for desc in self.paymentDescs:
			descModel.append((desc,))
		
		for person in self.account.getPeople():
			self.paidByCombo.append_text(person.getName())
			
		self.categoryCombo.append_text("None")
		self.categoryCombo.set_active(0)
		for category in self.account.getCategories():
			self.categoryCombo.append_text(category.getName())
			
		self.window.show_all()
		
	def OnOk(self, widget):
		value = self.valueSpinButton.get_text()
		date = self.dateEntry.get_text()
		desc = self.descriptionEntry.get_active_text()
		category = self.categoryCombo.get_active_text()
		paid = self.paidByCombo.get_active_text()
		comments = self.commentsTextView.get_buffer().get_property("text")
		
		msg = None
		if not Utils.isValidDateStr(date):
			msg = "Please enter a date in the format YYYY-MM-DD."
		elif category == "None" and not paid:
			msg = "Please select the person that paid for this bill."
		elif category != "None":
			cate = self.account.findCategory(category)
			if not cate.getPaidBy() and not paid:
				msg = "The chosen category does not specify the payee.\n"
				msg += "Please select the person that paid for this bill."
				
		try:
			self.shareWidget.GetProfile().calculateShares(value)
		except ShareProfile.OverTotalException:
			msg = "The sum of all the shared values cannot be greater than the total value of %.2f." % Dec(value)
		except ShareProfile.UnderTotalException:
			msg = "The sum of all the shared values cannot be less than the total value of %.2f." % Dec(value)
		
		if msg:
			InterfaceUtils.ShowErrorDialog(self.window, msg)
			return
		
		if paid == "Anyone":
			paid = None
		
		if category == "None":
			self.addPaymentCb(self.ID, value, date, desc, comments, paid, self.shareWidget.GetProfile())
		else:
			self.addPaymentCb(self.ID, value, date, desc, comments, paid, category)
		
		self.window.destroy()
	
	def OnCancel(self, widget, event=None):
		self.window.destroy()
		
	def OnValueChanged(self, widget):
		self.shareWidget.SetTotal(self.valueSpinButton.get_text())
	
	def OnCategoryChanged(self, widget):
		text = self.categoryCombo.get_active_text()
		if text == "None":
			self.paidByCombo.set_sensitive(True)
			self.shareWidget.set_sensitive(True)
		else:
			cate = self.account.findCategory(text)
			
			if not cate.getPaidBy():
				self.paidByCombo.set_active(-1)
				self.paidByCombo.set_sensitive(True)
			else:
				index = self.account.getPeople().index(cate.getPaidBy())
				self.paidByCombo.set_active(index)
				self.paidByCombo.set_sensitive(False)
			
			self.shareWidget.SetProfile(cate.getSharedBy())
			self.shareWidget.set_sensitive(False)
